package cn.fl.seccar.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import fl.constant.facade.framework.constant.DictionaryConstant;
import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.seccar.service.IAucCarInfoService;
import cn.fl.seccar.service.IAucCarQuoService;
import cn.fl.seccar.vo.AucCarInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.vo.SysUlFilesRecVO;

import com.alibaba.fastjson.JSONObject;

import fl.seccar.facade.auccar.condition.AucCarInfoQC;
import fl.seccar.facade.auccar.constant.AucCarInfoConstant;

/**
 * @Description: 竞拍车辆信息表 控制层
 */
@Controller
@RequestMapping("/auccar/aucCarInfo")
public class AucCarInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AucCarInfoController.class);

	/**
	 * AucCarInfo 服务层BEAN
	 */
	@Autowired
	private IAucCarInfoService aucCarInfoService;

	@Autowired
	private IAucCarQuoService aucCarQuoService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("seccar/aucCarInfo/aucCarInfoList");
		try {
			String sysCd = CurrentThreadContext.getFlServiceSysCd();
			String orgCd = CurrentThreadContext.getCurrentOrgCd();
			//售出状态
			String ynCd = PropertiesCacheUtils.getProperty(DictionaryConstant.CODE_SYS_YES_NO_CD);
			List<KeyValueVO> IsSeldNmList = this.sysDictionaryApiService.getKvList(ynCd, sysCd, orgCd);
			if (CollectionUtils.isNotEmpty(IsSeldNmList)) {
				view.addObject("IsSeldNmList", IsSeldNmList);
			}

			//车辆状态
			String prdStsCd = PropertiesCacheUtils.getProperty(DictionaryConstant.PRD_STS_CD);
			List<KeyValueVO> PrdStsCdNmList = this.sysDictionaryApiService.getKvList(prdStsCd, sysCd, orgCd);
			if (CollectionUtils.isNotEmpty(PrdStsCdNmList)) {
				view.addObject("PrdStsCdNmList", PrdStsCdNmList);
			}

		} catch (Exception e) {
			BaseLogUtils.error(logger, "toRcCstRhLvlTaskListPage", "获取数据字段错误", e);
		}
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddOrModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public ModelAndView toAddOrModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String detailFlag = request.getParameter("detailFlag");
		ModelAndView view = new ModelAndView("seccar/aucCarInfo/aucCarInfoAddOrModify");
		List<KeyValueVO> yNList = this.aucCarInfoService.searchYNList();
		view.addObject("id", id);
		view.addObject("detailFlag", detailFlag);
		view.addObject("yNList", yNList);
		BaseLogUtils.info(logger, "toAddOrModifyPage", "跳转到新增修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String prdNm = request.getParameter("prdNm");
		String searchPaySchNo = request.getParameter("searchPaySchNo");
		String searchPrdStsCd = request.getParameter("searchPrdStsCd");
		String searchIsSeld = request.getParameter("searchIsSeld");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		AucCarInfoQC qc = new AucCarInfoQC();
		if (StringUtils.isNotEmpty(prdNm)) {
			qc.setPrdNm(prdNm);
		}
		//支付表号
		if (StringUtils.isNotBlank(searchPaySchNo)) {
			qc.setPaySchNo(searchPaySchNo);
		}
		//车辆状态
		if (StringUtils.isNotBlank(searchPrdStsCd)) {
			qc.setPrdStsCd(Integer.parseInt(searchPrdStsCd));
		}
		//售出状态
		if (StringUtils.isNotBlank(searchIsSeld)) {
			qc.setIsSeld(Integer.parseInt(searchIsSeld));
		}
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		page.setCondition(qc);
		Pager pager = this.aucCarInfoService.searchListPage(page);
		List<AucCarInfoVO> list = (List<AucCarInfoVO>) pager.getResultList();
		ListPageVO<AucCarInfoVO> listPage = new ListPageVO<AucCarInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 修改(新增)
	 */
	@RequestMapping(value = "/addOrModify.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object addOrModify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);

		AucCarInfoVO entity = null;
		try {
			entity = getAucCarInfoParameters(request);
			if(StringUtils.isNotBlank(id)){
				entity.setId(Long.valueOf(id));
				entity.setMdfTm(new Date());
				entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				boolean success = this.aucCarInfoService.modify(entity);
				if(!success){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
					BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				}
				BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}else{
				entity.setPrdStsCd(AucCarInfoConstant.PRD_STS_CD_0);
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				entity.setSysCd(CurrentThreadContext.getCurrentSysCd());
				entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
				entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
				Long carId = this.aucCarInfoService.add(entity);
				result.setData(carId);
				BaseLogUtils.info(logger, "add", "新增数据.[carId="+carId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "addOrModify", "操作失败. DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addOrModify", "操作失败. DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.aucCarInfoService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			AucCarInfoVO vo = this.aucCarInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		AucCarInfoVO entity = null;
		try {
			entity = new AucCarInfoVO();
			//TODO ADD PARAM
			Long id = this.aucCarInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/confirmBatch.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object confirmBatch(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		String stValidDt = request.getParameter("stValidDt");
		String endValidDt = request.getParameter("endValidDt");
		String state = request.getParameter("state");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);

		AucCarInfoVO entity = null;
		try {
			entity = new AucCarInfoVO();
			String[] strs = ids.split(",");
			List<Long> prdIdList = new ArrayList<Long>();
			for(String id:strs){
				prdIdList.add(Long.valueOf(id));
				entity.setId(Long.valueOf(id));
				if(state.equals("0")){
					if(DateUtils.formatStringToDate(stValidDt, DateUtils.YYYY_MM_DDHHMM).before(new Date())){
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "上架时间不能小于当前时间");
					}
					if(DateUtils.formatStringToDate(endValidDt, DateUtils.YYYY_MM_DDHHMM).before(DateUtils.formatStringToDate(stValidDt, DateUtils.YYYY_MM_DDHHMM))){
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "下架时间不能小于上架时间");
					}
					entity.setPrdStsCd(AucCarInfoConstant.PRD_STS_CD_1);
					entity.setStValidDt(DateUtils.formatStringToDate(stValidDt, DateUtils.YYYY_MM_DDHHMM));
					entity.setEndValidDt(DateUtils.formatStringToDate(endValidDt, DateUtils.YYYY_MM_DDHHMM));
				}else{
					entity.setPrdStsCd(AucCarInfoConstant.PRD_STS_CD_2);
					entity.setStValidDt(null);
					entity.setEndValidDt(null);
				}
				boolean success = this.aucCarInfoService.modify(entity);
				if(!success){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
					BaseLogUtils.info(logger, "confirmBatch", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				}
				int count = this.aucCarQuoService.updateByPrdIdList(prdIdList);


			}
			BaseLogUtils.info(logger, "confirmBatch", "修改成功.[ids="+ids+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "confirmBatch", "修改失败.[ids="+ids+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "confirmBatch", "修改失败.[ids="+ids+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	private AucCarInfoVO getAucCarInfoParameters(HttpServletRequest request){
		AucCarInfoVO vo = new AucCarInfoVO();
		String id = request.getParameter("id");
		String prdNm = request.getParameter("prdNm");
		String paySchNo = request.getParameter("paySchNo");
		String engNo = request.getParameter("engNo");
		String vin = request.getParameter("vin");
		String carLicNo = request.getParameter("carLicNo");
		String rgnPrCd = request.getParameter("regStdProvCd");
		String rgnCyCd = request.getParameter("regStdCityCd");
		String isSeld = request.getParameter("isSeld");
		String stValidDt = request.getParameter("stValidDt");
		String endValidDt = request.getParameter("endValidDt");
		String fileParams = request.getParameter("fileParams");//文件资料

		if(StringUtils.isBlank(id)&&StringUtils.isNotBlank(stValidDt)&&DateUtils.formatStringToDate(stValidDt, DateUtils.YYYY_MM_DDHHMM).before(new Date())){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "上架时间不能小于当前时间");
		}

		if(StringUtils.isBlank(id)&&StringUtils.isNotBlank(endValidDt)&&StringUtils.isBlank(stValidDt)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "下架时间不能小于上架时间");
		}

		if(StringUtils.isBlank(id)&&StringUtils.isNotBlank(endValidDt)&&DateUtils.formatStringToDate(endValidDt, DateUtils.YYYY_MM_DDHHMM).before(DateUtils.formatStringToDate(stValidDt, DateUtils.YYYY_MM_DDHHMM))){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "下架时间不能小于上架时间");
		}

		if(StringUtils.isNotBlank(prdNm)){
			vo.setPrdNm(prdNm);
		}
		if(StringUtils.isNotBlank(paySchNo)){
			vo.setPaySchNo(paySchNo);
		}
		if(StringUtils.isNotBlank(engNo)){
			vo.setEngNo(engNo);
		}
		if(StringUtils.isNotBlank(vin)){
			vo.setVin(vin);
		}
		if(StringUtils.isNotBlank(carLicNo)){
			vo.setCarLicNo(carLicNo);
		}
		if(StringUtils.isNotBlank(rgnPrCd)){
			vo.setRgnPrCd(rgnPrCd);
		}
		if(StringUtils.isNotBlank(rgnCyCd)){
			vo.setRgnCyCd(rgnCyCd);
		}
		if(StringUtils.isNotBlank(isSeld)){
			vo.setIsSeld(Integer.valueOf(isSeld));
		}
		if(StringUtils.isNotBlank(stValidDt)){
			vo.setStValidDt(DateUtils.formatStringToDate(stValidDt, DateUtils.YYYY_MM_DDHHMM));
		}
		if(StringUtils.isNotBlank(endValidDt)){
			vo.setEndValidDt(DateUtils.formatStringToDate(endValidDt, DateUtils.YYYY_MM_DDHHMM));
		}

		if(StringUtils.isNotBlank(fileParams)){
			//解析附件上传信息
			JSONArray arry = JSONArray.fromObject(fileParams);
			List<SysUlFilesRecVO> uploadFilesRecVOs = new ArrayList<SysUlFilesRecVO>();
			if(arry.size()>0){
				for(int i=0;i<arry.size();i++){
					net.sf.json.JSONObject jsonObject = arry.getJSONObject(i);
					SysUlFilesRecVO sysUlFilesRecVO = new SysUlFilesRecVO();
					sysUlFilesRecVO.setFileNm(jsonObject.getString("fileNm"));
					sysUlFilesRecVO.setFilePath(jsonObject.getString("filePath"));
					sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
					sysUlFilesRecVO.setOrgCd(PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG);
					uploadFilesRecVOs.add(sysUlFilesRecVO);
				}
				vo.setUploadFilesRecVOs(uploadFilesRecVOs);
			}
		}
		return vo;
	}

	@RequestMapping(value = "/exportCarInfoExcel.do", method = {RequestMethod.POST})
	@ResponseBody
	public DataResultVO exportCarInfoExcel(HttpServletRequest request, HttpServletResponse response) {
		String prdNm = request.getParameter("prdNm");
		String searchPaySchNo = request.getParameter("searchPaySchNo");
		String searchPrdStsCd = request.getParameter("searchPrdStsCd");
		String searchIsSeld = request.getParameter("searchIsSeld");

		AucCarInfoQC qc = new AucCarInfoQC();
		if (StringUtils.isNotEmpty(prdNm)) {
			qc.setPrdNm(prdNm);
		}
		//支付表号
		if (StringUtils.isNotBlank(searchPaySchNo)) {
			qc.setPaySchNo(searchPaySchNo);
		}
		//车辆状态
		if (StringUtils.isNotBlank(searchPrdStsCd)) {
			qc.setPrdStsCd(Integer.parseInt(searchPrdStsCd));
		}
		//售出状态
		if (StringUtils.isNotBlank(searchIsSeld)) {
			qc.setIsSeld(Integer.parseInt(searchIsSeld));
		}
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		return this.aucCarInfoService.exportCarInfoList(qc);
	}
}

